package com.yc.tomcat.core;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLDecoder;

import com.yc.tomcat.utils.StringUtil;

public class ServerService implements Runnable {
	private Socket sk = null;
	private InputStream is;
	private OutputStream os;
	
	protected static String jsessionId = null;

	public ServerService(Socket sk) {
		this.sk = sk;
	}

	@Override
	public void run() {
		try {
			this.is = sk.getInputStream();
			this.os = sk.getOutputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// TODO 解析请求
		ServletRequest request = new HttpServletRequest(is);

		// TODO 获取请求的资源地址
		String url = request.getUrl();
//		System.out.println(url);

		if (!StringUtil.checkNull(url)) {
			try {
				url = URLDecoder.decode(url, "utf-8"); // 避免中文乱码
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		
		String projectName = "/abc";
		if (url.indexOf("/", 1) > 0) {
			projectName = url.substring(0, url.indexOf("/", 1));
		}
		
		// TODO 处理并响应请求
		ServletResponse response = new HttpServletResponse(projectName, os);
		if (url.contentEquals("/favicon.ico")) {  // 如果页面没有设定logo 则服务器会自动访问这个作为logo
			url = "/abc/images/logo.png";
			response.sendRedirect(url);
			return;
		}
		
		// TODO 判断请求是静态还是动态   (首先全部视为动态，然后查看有无servlet)
		String clazz = ParseUrlPattern.getServletClass(url);  // 通过url获取处理的servlet
		if (StringUtil.checkNull(clazz)) {  // 如果没有则当成静态资源处理
			response.sendRedirect(url);
			return;
		}
		
		// 如果有则需要先加载类
		URLClassLoader loader = null;
		URL classPath = null;
		try {
			classPath = new URL("file", null, ContantInfo.BASE_PATH + projectName + "\\WEB-INF\\classess");
			loader = new URLClassLoader(new URL[] {classPath});
			
			// 加载这个类，通过创建的类加载器
			Class<?> cls = loader.loadClass(clazz);
			
			// 判断这个类是否是一个servlet实例
			Servlet servlet = (Servlet) cls.newInstance();
			if (servlet != null && servlet instanceof Servlet) {
				servlet.init();
				servlet.service(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
			error500(e);
		}

	}

	private void error500(Exception e) {
		String response = "HTTP/1.1 500 Error\r\n;Content-Length:" + e.getMessage().getBytes().length + "\r\n\r\n";
		response += e.getMessage();
		try {
			os.write(response.getBytes());
			os.flush();
		} catch (IOException e1) {
			e1.printStackTrace();
		} finally {
			if (os != null) {
				try {
					os.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
	}

}
